package net.cnki.sunny.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login.html").loginProcessingUrl("/login")
                .successHandler(SecurityAuthenticationSuccessHandler()).failureHandler(new SecurityAuthenticationFailureHandler())
                .and()
                .logout();
        //去除CSRF 和 X-Frame-Options
        http.csrf().disable().headers().frameOptions().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/login.html", "/js/**", "/css/**", "/images/**");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(SecurityUserDetailService()).passwordEncoder(new SecurityPasswordEncoder());
    }

    @Bean
    protected SecurityUserDetailService SecurityUserDetailService() {
        return new SecurityUserDetailService();
    }

    @Bean
    protected SecurityAuthenticationSuccessHandler SecurityAuthenticationSuccessHandler(){return new SecurityAuthenticationSuccessHandler();}
}
